package com.bosssoft.ecds.msg.config;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;

/**
 * @author zhangxiaohui
 */
@Configuration
@Slf4j
public class MybatisPlusConfig {

    @Resource
    private HttpServletRequest httpServletRequest;

    /**
     * 注册字段自动填充
     */
    @Bean
    public MetaObjectHandler getMetaObjectHandler() {

        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createTime", new Date(), metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
                this.setFieldValByName("operatorId", getAuthId(), metaObject);
                this.setFieldValByName("operator", getAuthNickname(), metaObject);
                this.setFieldValByName("version", 0, metaObject);
                this.setFieldValByName("logicDelete", false, metaObject);

            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
                this.setFieldValByName("operatorId", getAuthId(), metaObject);
                this.setFieldValByName("operator", getAuthNickname(), metaObject);
            }
        };
    }

    public int getAuthId() {
        String authIdStr = httpServletRequest.getHeader("auth_id");
        log.info("request.auth_id:" + authIdStr);
        int authId = -1;
        if (StringUtils.isNotBlank(authIdStr)) {
            authId = Integer.parseInt(authIdStr);
        }
        return authId;
    }

    public String getAuthNickname() {
        String authNickname = httpServletRequest.getHeader("auth_nickname");
        log.info("request.auth_nickname:" + authNickname);
        if (StringUtils.isBlank(authNickname)) {
            authNickname = "null";
        } else {
            byte[] decode = Base64.getDecoder().decode(authNickname);
            authNickname = new String(decode, StandardCharsets.UTF_8);
        }
        return authNickname;
    }


    /**
     * 乐观锁插件
     */
    @Bean
    public OptimisticLockerInterceptor getOptimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}